package 字符串.最长公共前缀;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/5/16 16:58
 * @description:
 * @version:
 */
public class Solution {
    public static void main(String[] args) {
        String[] strs = {"aa","aaa",""};
        System.out.println(longestCommonPrefix2(strs));
    }

    public static String longestCommonPrefix(String[] strs) {
        if (strs.length == 1) {
            return strs[0];
        }
        StringBuilder sb = new StringBuilder(strs[0]);
        for (int i = 1; i < strs.length; i++) {
            String tmp = strs[i];
            if (tmp.length() == 0) {
                return tmp;
            }
            for (int j = 0; j < tmp.length(); j++) {
                if (j < sb.length() && tmp.charAt(j) != sb.charAt(j)) {
                    sb = new StringBuilder(sb.substring(0, j));
                    break;
                }
                if (j == tmp.length() - 1 && sb.length() > tmp.length()) {
                    sb = new StringBuilder(tmp);
                }
            }
        }
        return sb.toString();
    }

    public static String longestCommonPrefix2(String[] strs) {
        if(strs.length == 0)
            return "";
        String ans = strs[0];
        for(int i =1;i<strs.length;i++) {
            int j=0;
            //要学会在for循环中间加条件
            for(;j<ans.length() && j < strs[i].length();j++) {
                if(ans.charAt(j) != strs[i].charAt(j))
                    break;
            }
            ans = ans.substring(0, j);
            if(ans.equals(""))
                return ans;
        }
        return ans;
    }

}
